package com.youbo.ysqd.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youbo.ysqd.model.Block;
import com.youbo.ysqd.tools.RedisCache;
import com.youbo.ysqd.event.SearchReceive;
import com.youbo.ysqd.tools.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class QdService {


    public static String BASE_API="https://carrier.wbtech.com";
    SimpleDateFormat sfm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    @Autowired
    RedisCache redisCache;


    private int tokenIndex=1;


    private ExecutorService fixedThreadPool = Executors.newCachedThreadPool();


    /**
     * 轮询 主账号
     */
    @Scheduled(cron = "*/120 * * * * ?")
    public void mainLogin(){
        try{
            if(null==SearchReceive.block||SearchReceive.block.getStarts()==0){
                return;
            }
            String username=SearchReceive.usernames[0];
            String ukey=username+":token";
            getList(ukey);
        }catch (Exception e){}
    }


    /**
     * 轮询
     */
    @Scheduled(cron = "*/${myconfig.time} * * * * ?")
    public void start(){

        if(null==SearchReceive.block||SearchReceive.block.getStarts()==0){
            return;
        }


        String date=new SimpleDateFormat("yyyyMMdd").format(new Date());

        Integer max=redisCache.getCacheObject(date+":max");
        if(null==max){
            max=0;
            redisCache.setCacheObject(date+":max",max, 3, TimeUnit.DAYS);
        }
        if(max>=SearchReceive.block.getDaymax()){
            log.info("超过了单日最大接单量");
            return;
        }

        if(SearchReceive.usernames.length<3){
            log.error("账号不能少于3个");
            return;
        }

        if(tokenIndex>=SearchReceive.usernames.length){
            tokenIndex=1;
        }

        String username=SearchReceive.usernames[tokenIndex];
        String ukey=username+":token";

        getList(ukey);

        tokenIndex++;
    }





    public class MyRunnable implements Runnable{
        private String url;
        private String json;
        private String token;
        private String key;

        public MyRunnable(String url,String json,String token,String key){
            this.url=url;
            this.json=json;
            this.token=token;
            this.key=key;
        }

        @Override
        public void run() {
            String response= HttpUtils.post(url, json,token);
            jiexi(response,key);
        }
    }



    /**
     * 获取列表
     */
    public void getList(String key){
        String date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        long sdate=System.currentTimeMillis();
        long edate=System.currentTimeMillis();
        try{
            sdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date+" 00:00:00").getTime();
            edate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date+" 23:59:59").getTime();
        }catch (Exception e){}


        /**
         * {"rqStart":1620576000000,"rqEnd":1620662399059,"operateType":1,"quoteType":0,
         * "billPlate":"曲沃县","startPlate":"曲沃","page":0,"sizePerPage":10}
         */
        Map<String,String> map=new ConcurrentHashMap<>();
        //map.put("parentCatalogId","1");

        map.put("billPlate","曲沃县");
        map.put("rqStart",sdate+"");
        map.put("rqEnd",edate+"");
        map.put("operateType","1");
        map.put("quoteType","0");
        map.put("page","0");
        map.put("sizePerPage", SearchReceive.block.getPagesize()+"");

        String token=redisCache.getCacheObject(key);

        MyRunnable myRunnable=new MyRunnable(BASE_API+"/api/pro/business/publish/carrier/carrierPublishList", JSON.toJSONString(map),token,key);

        fixedThreadPool.execute(myRunnable);// 多线程执行



    }

    /**
     * 解析数据
     * @param response
     * @param key
     */
    private void jiexi(String response,String key){

        String[] endPlates=null;
        try{
            if(null!=SearchReceive.block.getKeyWord()){
                endPlates=SearchReceive.block.getKeyWord().split(";");
            }
        }catch (Exception e){}

        JSONObject jo=null;
        try{
            jo=JSON.parseObject(response);
        } catch (Exception e){
            log.error("登录失败:"+response);
            return;
        }


        if(jo.getInteger("code")==2){
            login(key);
            log.error(key+" 重新登录一次:"+jo.getString("message"));
            return;
        }if(jo.getInteger("code")==1){
            String message=jo.getString("message");
            log.error("访问出错:"+message);

            if(message.indexOf("频繁")>=0){
                Block block=redisCache.getCacheObject("ysqd_myuser");
                if(null!=block){
                    block.setStarts(0);
                    SearchReceive.block=block;
                    block.setTip(jo.getString("message"));
                    redisCache.setCacheObject("ysqd_myuser",block);
                }
            }
            return;
        }else if(jo.getInteger("code")!=0){
            log.error("查询失败:"+jo.getString("message"));
            return;
        }


        JSONObject data=jo.getJSONObject("data");
        if(null==data){
            log.error("本次未查询到数据");
            return;
        }
        int total=data.getInteger("totalElements");

        //log.info("扫描中,本次扫描到订单数量:"+total);

        if(total<=0){
            log.info("暂无数据:");
            return;
        }
        JSONArray ja=data.getJSONArray("content");


        log.info("用户"+key+"  根据条件查询到总订单"+total+"条 当前第一页"+ja.size()+"条 正在筛选推荐订单 ");



        Integer publishId,appointTeamType,appointTeamId;
        JSONObject item;
        String endPlate;

        for(int i=0;i<ja.size();i++){
            item=ja.getJSONObject(i);
            publishId=item.getInteger("publishId");
            appointTeamType=item.getInteger("appointTeamType");
            appointTeamId=item.getInteger("appointTeamId");
            endPlate=item.getString("endPlate");

            if(null==appointTeamType||null==appointTeamId||null==publishId){
                continue;
            }

            if(appointTeamType==4&&appointTeamId>0){
                log.info("找到 推荐货源 编号:"+publishId +" 找到时间:"+sfm.format(new Date()));

                boolean istg=false;
                if(null!=endPlate&&null!=endPlates&&endPlates.length>0){
                    for (int x=0;x<endPlates.length;x++){
                        if(endPlate.contains(endPlates[x])&&!"".equals(endPlates[x].trim())){
                            istg=true;
                        }
                    }
                }

                if(istg){
                    log.info("匹配到过滤目的地: 关键词列表:"+JSON.toJSON(endPlates)+"  自动跳过目的地:"+endPlate +" 货源编号:"+publishId);
                    continue;
                }


                Map<String,Boolean> idsMap=redisCache.getCacheObject("idsmap");
                if(null==idsMap){
                    idsMap=new ConcurrentHashMap<>();
                    redisCache.setCacheObject("idsmap",idsMap);
                }
                Boolean fa=idsMap.get(publishId);
                if(null!=fa&&fa){
                    log.info("货源编号:"+publishId+" 已经抢单完成 无需重复提交");
                    continue;
                }


                doSubmit(publishId+"",key);

                //MyRunnable2 myRunnable2=new MyRunnable2(mkey);
                //fixedThreadPool.execute(myRunnable2);

            }
        }


    }


    /**
     * 提交抢单
     * @param publishId  订单编号
     */
    public void doSubmit(String publishId,String key) {

        String username=SearchReceive.usernames[0];
        String ukey=username+":token";

        String token=redisCache.getCacheObject(ukey);
        if(null==token){
            login(key);
            token=redisCache.getCacheObject(key);
        }

        String date=new SimpleDateFormat("yyyyMMdd").format(new Date());

        Integer max=redisCache.getCacheObject(date+":max");
        if(null==max){
            max=0;
            redisCache.setCacheObject(date+":max",max, 3, TimeUnit.DAYS);
        }
        Map<String,Boolean> idsMap=redisCache.getCacheObject("idsmap");
        if(null==idsMap){
            idsMap=new ConcurrentHashMap<>();
            redisCache.setCacheObject("idsmap",idsMap);
        }

        if(max>=SearchReceive.block.getDaymax()){
            log.info("超过了单日最大接单量");
            return;
        }


        String json="{\"publishId\":\""+publishId+"\",\"operateType\":\"web\",\"ifZntsFlag\":0}";


        String response = HttpUtils.post(BASE_API + "/api/pro/business/publish/carrier/grabBill", json,token);

        JSONObject jo = null;
        try {
            jo = JSON.parseObject(response);
        } catch (Exception e) {
            log.error("抢单失败:" + response);
            return;
        }

        if(jo.getInteger("code")==2){
            login(key);
            log.error(key+" 重新登录一次:"+jo.getString("message"));
            return;
        }

        if (jo.getInteger("code") != 0) {
            log.error("货源编号:"+publishId+"  code:"+jo.getInteger("code")+" 抢单失败:" + jo.getString("message"));
            return;
        }


        idsMap.put(""+publishId,true);
        redisCache.setCacheObject(date+":max",(max+1), 3, TimeUnit.DAYS);
        redisCache.setCacheObject("idsmap",idsMap);

        log.info("抢单成功:"+response);

    }

    /**
     * 登录
     */
    public void login(String key){
       Map<String,Object> map=new ConcurrentHashMap<>();
        Map<String,Object> deviceInfo=new ConcurrentHashMap<>();

        deviceInfo.put("platform",2);
        deviceInfo.put("sdkVersion","14.4.2");
        deviceInfo.put("brand","iPhone");
        deviceInfo.put("cameraAuthorized",0);
        deviceInfo.put("version","3.1.10");
        deviceInfo.put("locationAuthorized",0);

        deviceInfo.put("latitude","35.646518");
        deviceInfo.put("longitude","111.500463");

        String username=key.replace(":token","");
        map.put("username", username);
        map.put("password", SearchReceive.block.getPassword());

        deviceInfo.put("imeiCode","C4354775-B08C-4FD8-B995-CE597FE36F7F");
        deviceInfo.put("model","iPhone 12");


        map.put("deviceInfo",deviceInfo);
        map.put("authType","0");

        /**
         * {
         * 	"code": 0,
         * 	"message": null,
         * 	"data": {
         * 		"tk": "48e7eda4-a8a9-4d95-8dae-69889fd27dff",
         * 		"ltk": null,
         * 		"roles": ["2"]
         *        }
         * }
         */

        String response= HttpUtils.post("https://napp-api.wbtech.com/v1/login", JSON.toJSONString(map),null);

       JSONObject jo=null;
       try{
           jo=JSON.parseObject(response);
       } catch (Exception e){
           log.error("登录失败:"+response);
       }

       if(null==jo){
           return;
       }

       //{"code":0,"message":null,"data":{"tk":"8b6addf1-b440-4203-9f7d-35d7b86111b3","ltk":null,"roles":["2"]}}
       if(jo.getInteger("code")!=0){
           log.error("登录失败:"+jo.getString("message"));
           return;
       }
       String tk= jo.getJSONObject("data").getString("tk");
       redisCache.setCacheObject(key,tk,2,TimeUnit.DAYS);


       log.info("用户"+key+" 登录成功:"+response);
    }





}
